import React from 'react';

import './styles/FileInput.less';

export default class FileInput extends React.Component {

	constructor(props) {
		super(props);
		this.state = {};
	}

	consume(reader) {
		var total = 0
		return pump()
		function pump() {
			return reader.read().then(({done, value}) => {
				if (done) {
					console.log(done);
					return
				}
				total += value.byteLength
				console.log(`received ${value.byteLength} bytes (${total} bytes in total)`)
				return pump()
			})
		}
	}

	handleFileChange(e) {
		let formData = new FormData();
		formData.append('fileType', this.props.accept);
		formData.append('file', e.target.files[0]);
		fetch('/upload', {
			method: 'POST',
			body: formData
		})
		.then((res) => res.json())
		.then((json) => this.props.onChange && this.props.onChange(json.url))
		.catch((ex) => this.props.onFailed && this.props.onFailed(ex));
	}

	render() {
		let {className, children, accept, onChange, ...props} = this.props;
		return (
			<div className={`ComponentFileInput ${className || ''}`} {...props}>
				{children}
				<input type="file" accept={accept} onChange={this.handleFileChange.bind(this) }/>
			</div>
		)
	}
}

FileInput.propTypes = {
	onChange: React.PropTypes.func,
	onProgress: React.PropTypes.func,
	onFailed: React.PropTypes.func,
};
